﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tododoo.Lib
{
    public static class PostOffice
    {
        private static Dictionary<Mail, List<WeakReference>> recepients = new Dictionary<Mail, List<WeakReference>>();

        public static void Subscribe(Mail mail, IRecepient recepient)
        {
            if (mail == null) { throw new ArgumentNullException("mail"); }
            if (recepient == null) { throw new ArgumentNullException("recepient"); }

            if (!recepients.ContainsKey(mail)) { recepients.Add(mail, new List<WeakReference>()); }
            recepients[mail].Add(new WeakReference(recepient));
        }

        public static void Send(Mail mail, object attachment)
        {
            if (mail == null) { throw new ArgumentNullException("mail"); }
            if (!recepients.ContainsKey(mail)) { return; }

            foreach (var recepient in recepients[mail])
            {
                if (recepient.IsAlive)
                {
                    // true == handled, therefore we break this
                    if (((IRecepient)recepient.Target).GotMail(mail, attachment) == true) break;
                }
            }
        }
    }
}
